/**
 * Copyright (C) 2011 The Android Open Source Project 
 * Emial : guoyil199@163.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package com.example.app.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.util.Log;

/**
 * @author Administrator
 * @Email guoyil199@163.com
 * @version V1.0
 * @Date 
 * @Title <B>todo</B>
 * @Description <pre>
 * todo
 * </pre>
 */

public class CMDExecute {

	public CMDExecute() {
	}

	public synchronized String run(String[] cmd, String workdirectory)
			throws IOException {
		String result = "";
		try {
			ProcessBuilder builder = new ProcessBuilder(cmd);
			InputStream in = null;
			// 设置一个路径
			if (workdirectory != null) {
				builder.directory(new File(workdirectory));
				builder.redirectErrorStream(true);
				Process process = builder.start();
				in = process.getInputStream();
				byte[] re = new byte[1024];
				while (in.read(re) != -1)
					result = result + new String(re);
			}
			if (in != null) {
				in.close();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	// 操作系统版本
	public static String fetch_version_info() {
		String result = null;
		CMDExecute cmdexe = new CMDExecute();
		try {
			String[] args = { "/system/bin/cat", "/proc/version" };
			result = cmdexe.run(args, "system/bin/");
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	// 系统信息
	public static StringBuffer buffer = null;

	private static String initProperty(String description, String propertyStr) {
		if (buffer == null) {
			buffer = new StringBuffer();
		}
		buffer.append(description).append(":");
		buffer.append(System.getProperty(propertyStr)).append(" ");
		return buffer.toString();
	}

	private static String getSystemProperty() {
		buffer = new StringBuffer();
		initProperty("java.vendor.url", "java.vendor.url");
		initProperty("java.class.path", "java.class.path");
		return buffer.toString();
	}

	// 运营商信息
	public static String fetch_tel_status(Context cx) {
		String result = null;
		TelephonyManager tm = (TelephonyManager) cx
				.getSystemService(Context.TELEPHONY_SERVICE);
		String str = " ";
		str += "DeviceId(IMEI) = " + tm.getDeviceId() + " ";
		str += "DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + " ";
		// TODO: Do something ...
		int mcc = cx.getResources().getConfiguration().mcc;
		int mnc = cx.getResources().getConfiguration().mnc;
		str += "IMSI MCC (Mobile Country Code): " + String.valueOf(mcc) + " ";
		str += "IMSI MNC (Mobile Network Code): " + String.valueOf(mnc) + " ";
		result = str;
		return result;
	}

	// 获取CPU信息
	public static String fetch_cpu_info() {
		String result = null;
		CMDExecute cmdexe = new CMDExecute();
		try {
			String[] args = { "/system/bin/cat", "/proc/cpuinfo" };
			result = cmdexe.run(args, "/system/bin/");
			Log.i("result", "result=" + result);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	// 获取内存信息
	public static String getMemoryInfo(Context context) {
		StringBuffer memoryInfo = new StringBuffer();
		final ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
		activityManager.getMemoryInfo(outInfo);
		memoryInfo.append(" Total Available Memory :")
				.append(outInfo.availMem >> 10).append("k");
		memoryInfo.append(" Total Available Memory :")
				.append(outInfo.availMem >> 20).append("k");
		memoryInfo.append(" In low memory situation:")
				.append(outInfo.lowMemory);
		String result = null;
		CMDExecute cmdexe = new CMDExecute();
		try {
			String[] args = { "/system/bin/cat", "/proc/meminfo" };
			result = cmdexe.run(args, "/system/bin/");
		} catch (IOException ex) {
			Log.i("fetch_process_info", "ex=" + ex.toString());
		}
		return (memoryInfo.toString() + " " + result);
	}

	// 获取磁盘信息
	public static String fetch_disk_info() {
		String result = null;
		CMDExecute cmdexe = new CMDExecute();
		try {
			String[] args = { "/system/bin/df" };
			result = cmdexe.run(args, "/system/bin/");
			Log.i("result", "result=" + result);
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return result;
	}

	// 获取网络信息
	public static String fetch_netcfg_info() {
		String result = null;
		CMDExecute cmdexe = new CMDExecute();
		try {
			String[] args = { "/system/bin/netcfg" };
			result = cmdexe.run(args, "/system/bin/");
		} catch (IOException ex) {
			Log.i("fetch_process_info", "ex=" + ex.toString());
		}
		return result;
	}

	// 获取显示频信息
	public static String getDisplayMetrics(Context cx) {
		String str = "";
		DisplayMetrics dm = new DisplayMetrics();
		dm = cx.getApplicationContext().getResources().getDisplayMetrics();
		int screenWidth = dm.widthPixels;
		int screenHeight = dm.heightPixels;
		float density = dm.density;
		float xdpi = dm.xdpi;
		float ydpi = dm.ydpi;
		str += "The absolute width: " + String.valueOf(screenWidth) + "pixels ";
		str += "The absolute heightin: " + String.valueOf(screenHeight)
				+ "pixels ";
		str += "The logical density of the display. : "
				+ String.valueOf(density) + " ";
		str += "X dimension : " + String.valueOf(xdpi) + "pixels per inch ";
		str += "Y dimension : " + String.valueOf(ydpi) + "pixels per inch ";
		return str;
	}

	// 获取正在运行的Service信息
	// 正在运行的服务列表
	public static String getRunningServicesInfo(Context context) {
		StringBuffer serviceInfo = new StringBuffer();
		final ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningServiceInfo> services = activityManager
				.getRunningServices(100);
		Iterator<RunningServiceInfo> l = services.iterator();
		while (l.hasNext()) {
			RunningServiceInfo si = (RunningServiceInfo) l.next();
			serviceInfo.append("pid: ").append(si.pid);
			serviceInfo.append(" process: ").append(si.process);
			serviceInfo.append(" service: ").append(si.service);
			serviceInfo.append(" crashCount: ").append(si.crashCount);
			serviceInfo.append(" clicentCount: ").append(si.clientCount);
			serviceInfo.append(" activeSince:").append(si.activeSince);
			serviceInfo.append(" lastActivityTime: ").append(
					si.lastActivityTime);
			serviceInfo.append(" ");
		}
		return serviceInfo.toString();
	}

	// 查看软件信息
	public ArrayList fetch_installed_apps(Context context) {
		List<ApplicationInfo> packages = context.getPackageManager()
				.getInstalledApplications(0);
		ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>(
				packages.size());
		Iterator<ApplicationInfo> l = packages.iterator();
		while (l.hasNext()) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			ApplicationInfo app = (ApplicationInfo) l.next();
			String packageName = app.packageName;
			String label = " ";
			try {
				label = context.getPackageManager().getApplicationLabel(app)
						.toString();
			} catch (Exception e) {
				Log.i("Exception", e.toString());
			}
			map = new HashMap<String, Object>();
			map.put("name", label);
			map.put("desc", packageName);
			list.add(map);
		}
		return list;
	}

	// 获取正在运行的Task信息

	public static String getRunningTaskInfo(Context context) {
		StringBuffer sInfo = new StringBuffer();
		final ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasks = activityManager.getRunningTasks(100);
		Iterator<RunningTaskInfo> l = tasks.iterator();
		while (l.hasNext()) {
			RunningTaskInfo ti = (RunningTaskInfo) l.next();
			sInfo.append("id: ").append(ti.id);
			sInfo.append(" baseActivity: ").append(
					ti.baseActivity.flattenToString());
			sInfo.append(" numActivities: ").append(ti.numActivities);
			sInfo.append(" numRunning: ").append(ti.numRunning);
			sInfo.append(" description: ").append(ti.description);
			sInfo.append(" ");
		}
		return sInfo.toString();
	}

	// 获取正在运行的进程信息

	public static String fetch_process_info() {
		Log.i("fetch_process_info", "start. . . . ");
		String result = null;
		CMDExecute cmdexe = new CMDExecute();
		try {
			String[] args = { "/system/bin/top", "-n", "1" };
			result = cmdexe.run(args, "/system/bin/");
		} catch (IOException ex) {
			Log.i("fetch_process_info", "ex=" + ex.toString());
		}
		return result;
	}

	public static void file_explorer(Context ctx) {
		// 文件浏览器
		Intent intent = new Intent();
		// /intent.setClass(ctx, FSExplorer.class);
		ctx.startActivity(intent);

	}

	public static void system_info(Context ctx) {
		// 文件浏览器
		Intent intent = new Intent();
		// 查看系统信息实现
		intent.setClass(ctx, System.class);
		ctx.startActivity(intent);

	}

}
